//
//  RxDataSourceAutoTableVC.swift
//  CooperSwift_Example
//
//  Created by 计海峰 on 2021/5/13.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import UIKit
import RxSwift
import RxDataSources
import CooperSwift
import Then
import SnapKit
import Toast_Swift

// struct
class TestCellModel : NSObject, TableCellConfigProtocol {
    
    func once(_ target: UIView, cell: UITableViewCell) {
        
    }
    
    func every(_ target: UIView, cell: UITableViewCell) {
        
    }
    
    var model: Any?
    
    required init(_ model: Any?) {
        self.model = model
    }

    func cellCls() -> UITableViewCell.Type {
        return TestAutoCell.self
    }
    
    public typealias TargetType = UIView
    
}

class TableFormStackCellModel: NSObject, BindKeyProtocol, FormStackCellModelProtocol {
    func once(_ target: Array<UIView>, cell: UITableViewCell) {
        
    }
    
    func every(_ target: Array<UIView>, cell: UITableViewCell) {
        
    }
  
    var model: Any?
    var title = ""
    var subTitle = ""
    let disposeBag = DisposeBag()
    

    func configLeftImgV1(_ imageV: UIImageView) {
        imageV.standListIconConfig("settings", width: 18)
    }
    
    func configBgView(_ bgView: UIView, cell: UITableViewCell) {
        bgView.snp.updateConstraints {
            $0.height.equalTo(65)
        }
    }
    
    func configLeftLB1(_ lb: UILabel) {
        lb.standListTitleConfig("地址", widthConstraint: true)
    }
    
    func configRightImgV1(_ imageV: UIImageView) {
        imageV.standListIconConfig("more_image", width: 18)
    }
    
    func configRightView0(_ view: UIView) {
        view.isHidden = false
        view.snp.makeConstraints {
            $0.height.width.equalTo(4)
        }
    }
    
    func configLeftView0(_ view: UIView) {
        view.isHidden = false
        view.snp.makeConstraints {
            $0.height.width.equalTo(4)
        }
    }
    
    func configCenterContentTF(_ tf: UITextField) {
        tf.standListInputConfig()
        tf.text = self.showValue ?? ""
    }
    
    func configOnceCenterContentTF(_ tf: UITextField) {
        tf.placeholder = "请输入\(title)"
        tf.rx.text.distinctUntilChanged().subscribe(onNext: { [weak self] text in
            print(text as Any)
            self?.showValue = text
        }).disposed(by: disposeBag)
    }
    
    required init(_ model: Any?) {
        self.model = model
    }
    
    func cellCls() -> UITableViewCell.Type {
        return TableFormStackCell.self
    }
    
}

class TestControlModel: NSObject, ViewControlProtocol, ViewConsProtocol {
  
}


// MARK: - table view model
class RxDataSourceAutoTableVM: NSObject, UITableViewDelegate, TableViewModelProtocol, RefreshControllable, FormResultProtocol {

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return vm_tableView(tableView, heightForRowAt: indexPath)
    }
    
    func configDown() {
        toState(.loading)
        refresh()
    }
    
    func refresh() {
        print("refresh")
        PublicMethod.delay(1) {
            self.toState(.noData)
            self.sections.append(self.testItem())
            self.rx.refreshStatus.onNext(.endHeaderRefresh)
            self.rx.refreshStatus.onNext(.showFooter)
        }
    }
    
    func pullUp() {
        print("pull")
        PublicMethod.delay(1) {
            self.rx.refreshStatus.onNext(.endFooterRefresh)
        }
    }
    
    func imageControl(_ number: Int) -> TableShowImageConfig {
        let model = TableShowImageConfig().then {
            let width = (414 - 32.0)/3.0 - 0.01
            $0.vTopCons = 8
            $0.vLeftCons = 8
            $0.masksToBounds = true
//            $0.vRadius = 8
            $0.url = "https://dss1.bdstatic.com/kvoZeXSm1A5BphGlnYG/skin_zoom/\(number).jpg"
            $0.vWidthCons = CGFloat(width)
            $0.vHeightCons = CGFloat(width)
        }
        if number == 327 {
            model.vRadius = 8
        }
        if number == 322 {
            model.cornerRadii = .init(topLeft: 8, topRight: 0, bottomLeft: 0, bottomRight: 8)
        }
        return model
    }
    
    func testItem(_ i: Int = 1) -> SectionModel<Any, TableCellConfigProtocol> {
        
        let arr = [imageControl(320), imageControl(321), imageControl(322), imageControl(323), imageControl(324), imageControl(325), imageControl(326), imageControl(327), imageControl(328), imageControl(329)]
        var imagesModel = TableShowImagesConfig.init(arr)
        imagesModel.isDelay = true
        let imagsCellModel = TableShowImagesCellModel.init(imagesModel).then {
            $0.cellHeight = imagesModel.cellHeight
        }
        return SectionModel<Any, TableCellConfigProtocol>(model: "one \(i)", items: [
            TestCellModel.init("4"),
//            TestCellModel.init("5"),
            TestClasCellModel.init("8").addTargetKey("\(bindKey())").addTargetKey(self.parentKey, isTarget: false),
            imagsCellModel,
            TableFormStackCellModel.init("瑶海区").with {
                $0.title = "名字"
                $0.hintText = "请输入名字"
                let this = $0
                $0.validationBlock = {
                    if (this.showValue != nil && this.dataKey != nil) {
                        return ("key", "名字")
                    }
                    return nil
                }
                $0.dataKey = "testValidationBlock"
            },
            TestAutoTextInputCelllModel.init("").addTargetKey("\(bindKey())").addTargetKey(self.parentKey, isTarget: false),
            TableFormStackCellModel.init("瑶海区").with {
                $0.title = "作业位置"
                $0.hintText = "请选择临时位置"
                $0.dataKey = "location\(i + Int.random(in: Range(uncheckedBounds: (1, 10))))"
            },
            TableFormCellModel.init("1234")
        ])
        
    }
    
    
    @objc func sumbit() {
        let _ = self.checkSumbit { showWindowToast($0) }
        print(self.currentParams())
    }
    
    deinit {
        print("RxDataSourceAutoTableVM deinit")
    }
  
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        guard let block = serviceBlock else { return }
        if let vc = block(.controller) as? LazyLoadProtocol, let _ = cell as? TableShowImagesCell  {
            vc.addTask(indexPath) { index in
                guard let targetCell = cell as? TableShowImagesCell else { return false }
                targetCell.loadImagesActivity()
                return true
            }
        }
    }
    
}

// MARK: - vc
class RxDataSourceAutoTableVC: UIViewController, TableEnableProtocol, Refreshable, LazyLoadProtocol {
    
    let disposeBag = DisposeBag()
    
    var vm = ViewModelFactory.tableVM(RxDataSourceAutoTableVM.self)
    
    /// 指定构造器(Designated Initializer)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    /// 便利构造器(Convenience Initializer)
    convenience init() {
        self.init(nibName: nil, bundle: nil)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        configAll(vm, disposeBag: disposeBag, refreshConfig: .header, edges: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
    
//        noSleep()
        startObserve()
    }
    
    func noSleep() {
        //创建定时器 (保证runloop回调函数一直在执行)
        let displayLink = CADisplayLink(target: self, selector: #selector(notDoSomething))
        displayLink.add(to: .current, forMode: .common)
    }
    
    @objc func notDoSomething() {
        
    }
    
    deinit {
        print("RxDataSourceAutoTableVC deinit")
    }
    
}
